package com.atguigu.gmall.auth.service.impl;

import com.atguigu.gmall.auth.config.JwtProperties;
import com.atguigu.gmall.auth.feign.GmallUmsClient;
import com.atguigu.gmall.auth.service.AuthService;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.exception.AuthException;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.IpUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import com.atguigu.gmall.common.utils.RsaUtils;
import com.atguigu.gmall.ums.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @description:
 * @author: xie.zh
 * @create: 2021.03.29   14:15
 * @version: 1.0
 */
@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthServiceImpl implements AuthService {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private GmallUmsClient umsClient;

    @Override
    public void login(String loginName, String password, HttpServletRequest request, HttpServletResponse response) {
        //1、查询用户
        ResponseVo<UserEntity> userEntityResponseVo = umsClient.queryUser(loginName, password);
        UserEntity userEntity = userEntityResponseVo.getData();
        if (userEntity == null) {
            throw new AuthException("用户名或密码错误");
        }
        //2、组合jwt有效载荷 userid username ip
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", userEntity.getId());
        map.put("userName", userEntity.getUsername());
        map.put("ip", IpUtils.getIpAddressAtService(request));
        try {
            //3、生成token
            String token = JwtUtils.generateToken(map, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            //4、添加token到cookie
            CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), token, jwtProperties.getExpire());
            CookieUtils.setCookie(request, response, jwtProperties.getUnick(), userEntity.getNickname(),
                    jwtProperties.getExpire());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
